package com.lcz.fruitweb.web;


import com.lcz.fruitweb.service.FruitService;
import com.lcz.fruitweb.service.impl.FruitServiceImpl;
import lombok.SneakyThrows;
import model.Fruit;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 才智
 */
@WebServlet("/fruitAdd")
public class FruitAddServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        //获取用户输入，保存数据
        Fruit fruit = new Fruit();
        BeanUtils.populate(fruit, req.getParameterMap());

        ApplicationContext applicationContext = (ApplicationContext) getServletContext().getAttribute("applicationContext");
        FruitService fruitService = applicationContext.getBean("fruitService",FruitService.class);
        boolean ret = fruitService.saveFruit(fruit);
        if (ret) {
            resp.sendRedirect("fruitList");
        } else {
            req.getRequestDispatcher("fruitAdd.jsp").forward(req, resp);
        }
    }
}
